#!/usr/bin/env node

/**
 * ALYR.NET 智能体规则系统 - 自动依赖安装器
 * 版权所有 (c) 2020-2025 ALYR.NET
 * 联系方式: 邮箱 builder@alyr.net
 */

const fs = require('fs');
const path = require('path');
const { execSync, spawn } = require('child_process');
const chalk = require('chalk');

class AlyrAutoSetup {
  constructor() {
    this.packageJson = null;
    this.missingDeps = [];
    this.isCheckOnly = process.argv.includes('--check-only');
    this.isInstallOnly = process.argv.includes('--install-only');
  }

  // 🎯 主入口函数
  async run() {
<<<<<<< Updated upstream
    console.log(chalk.blue.bold('🚀 Builder.Alyr.Net 智能体规则系统 - 自动安装器 v4.0'));
=======
    console.log(chalk.blue.bold('🚀 Builder.Alyr.Net 智能体规则系统 - 自动安装器 V4.2.1'));
>>>>>>> Stashed changes
    console.log(chalk.gray('=' .repeat(60)));
    console.log(chalk.cyan('📞 技术支持: builder@alyr.net'));
    console.log(chalk.gray('=' .repeat(60)));
    
    try {
      // 1. 检查环境
      await this.checkEnvironment();
      
      // 2. 检查依赖
      await this.checkDependencies();
      
      // 3. 安装缺失依赖
      if (!this.isCheckOnly && this.missingDeps.length > 0) {
        await this.installMissingDependencies();
      }
      
      // 4. 验证安装
      await this.verifyInstallation();
      
      // 5. 显示完成信息
      this.showCompletionInfo();
      
    } catch (error) {
      console.error(chalk.red(`❌ 安装失败: ${error.message}`));
      console.log(chalk.yellow('📞 如需帮助，请联系: builder@alyr.net'));
      process.exit(1);
    }
  }

  // 🔍 检查环境
  async checkEnvironment() {
    console.log(chalk.cyan('🔍 检查运行环境...'));
    
    // 检查 Node.js 版本
    const nodeVersion = process.version;
    console.log(chalk.green(`✅ Node.js 版本: ${nodeVersion}`));
    
    // 检查 npm 版本
    try {
      const npmVersion = execSync('npm --version', { encoding: 'utf8' }).trim();
      console.log(chalk.green(`✅ npm 版本: ${npmVersion}`));
    } catch (error) {
      throw new Error('npm 未安装或不可用');
    }
    
    // 检查 package.json
    if (!fs.existsSync('package.json')) {
      throw new Error('未找到 package.json 文件');
    }
    
    this.packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8'));
    console.log(chalk.green(`✅ 项目: Builder.Alyr.Net 智能体代码规范检测工具 v${this.packageJson.version}`));
  }

  // 📦 检查依赖
  async checkDependencies() {
    console.log(chalk.cyan('\n📦 检查项目依赖...'));
    
    const allDeps = {
      ...this.packageJson.dependencies || {},
      ...this.packageJson.devDependencies || {}
    };
    
    this.missingDeps = [];
    
    for (const [depName, depVersion] of Object.entries(allDeps)) {
      try {
        require.resolve(depName);
        console.log(chalk.green(`✅ ${depName}`));
      } catch (error) {
        this.missingDeps.push({ name: depName, version: depVersion });
        console.log(chalk.red(`❌ ${depName} (缺失)`));
      }
    }
    
    if (this.missingDeps.length === 0) {
      console.log(chalk.green('\n🎉 所有依赖都已安装！'));
    } else {
      console.log(chalk.yellow(`\n⚠️  发现 ${this.missingDeps.length} 个缺失依赖`));
      
      if (this.isCheckOnly) {
        console.log(chalk.blue('\n💡 运行 npm run setup 自动安装缺失依赖'));
        return;
      }
    }
  }

  // 🔧 安装缺失依赖
  async installMissingDependencies() {
    if (this.missingDeps.length === 0) return;
    
    console.log(chalk.cyan('\n🔧 正在安装缺失依赖...'));
    
    // 显示即将安装的依赖
    console.log(chalk.yellow('即将安装:'));
    this.missingDeps.forEach(dep => {
      console.log(chalk.gray(`  - ${dep.name}@${dep.version}`));
    });
    
    try {
      // 使用 npm install 安装依赖
      console.log(chalk.blue('\n⏳ 执行 npm install...'));
      
      const installProcess = spawn('npm', ['install'], {
        stdio: 'inherit',
        shell: true
      });
      
      await new Promise((resolve, reject) => {
        installProcess.on('close', (code) => {
          if (code === 0) {
            resolve();
          } else {
            reject(new Error(`npm install 失败，退出码: ${code}`));
          }
        });
      });
      
      console.log(chalk.green('\n✅ 依赖安装完成！'));
      
    } catch (error) {
      throw new Error(`依赖安装失败: ${error.message}`);
    }
  }

  // ✅ 验证安装
  async verifyInstallation() {
    console.log(chalk.cyan('\n✅ 验证安装结果...'));
    
    // 重新检查依赖
    const allDeps = {
      ...this.packageJson.dependencies || {},
      ...this.packageJson.devDependencies || {}
    };
    
    let allInstalled = true;
    
    for (const depName of Object.keys(allDeps)) {
      try {
        require.resolve(depName);
        console.log(chalk.green(`✅ ${depName} 已安装`));
      } catch (error) {
        console.log(chalk.red(`❌ ${depName} 安装失败`));
        allInstalled = false;
      }
    }
    
    if (!allInstalled) {
      throw new Error('部分依赖安装失败，请手动检查');
    }
  }

  // 🎉 显示完成信息
  showCompletionInfo() {
    console.log(chalk.gray('\n' + '=' .repeat(60)));
    console.log(chalk.green.bold('🎉 Builder.Alyr.Net 智能体规则系统安装完成！'));
    console.log(chalk.gray('=' .repeat(60)));
    
    console.log(chalk.blue('\n📋 可用命令:'));
    console.log(chalk.cyan('  npm run ai:start     - 启动智能体（推荐）'));
    console.log(chalk.cyan('  npm run ai:check     - 规则检查'));
    console.log(chalk.cyan('  npm run ai:monitor   - 实时监控'));
    console.log(chalk.cyan('  npm run setup        - 重新安装依赖'));
    
    console.log(chalk.blue('\n📞 技术支持:'));
        console.log(chalk.yellow('  官网: https://gitee.com/Alyr_space/Builder.Alyr.Net'));
    
    console.log(chalk.blue('\n🚀 快速开始:'));
    console.log(chalk.green('  npm run ai:start'));
    
    console.log(chalk.gray('\n' + '=' .repeat(60)));
  }
}

// 🚀 主程序入口
async function main() {
  const setup = new AlyrAutoSetup();
  await setup.run();
}

// 导出模块
module.exports = { AlyrAutoSetup };

// 如果直接运行此脚本
if (require.main === module) {
  main().catch(error => {
    console.error(chalk.red(`❌ 程序异常: ${error.message}`));
    console.log(chalk.yellow('📞 技术支持: builder@alyr.net'));
    process.exit(1);
  });
}